﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ZUtil;
using EEGWin.ex;
using System.Text.RegularExpressions;
using EEGWin.dao;
using EEGWin.model;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using ZOpenGLControl;
using System.Net.Sockets;

namespace EEGWin
{
    public partial class MainFrame : CCWin.CCSkinMain
    {

        private UserDao userDao = new UserDao();

        private AutoResetEvent autoRest = new AutoResetEvent(false);
        private CollectionPip2 collectionPip;
        private bool isDisposed;

        //public delegate void EventReadDataItems(DataItem[] dataItems);
        //public event EventReadDataItems eventReadDataItems;

        private delegate void DG();
        public MainFrame()
        {
            InitializeComponent();

        }
        private void addMsg(String str)
        {
            Console.WriteLine(str);
        }
        private void keepConn()
        {
            collectionPip = new CollectionPip2(txt_swj_host.Text.Trim(), int.Parse(txt_swj_port.Text.Trim()), int.Parse(txt_swj_port2.Text.Trim()))
            {
                bs_btn_user = ByteUtil.stringToByte(txt_user_order.Text),
                bs_btn_step1 = ByteUtil.stringToByte(txt_step1_order.Text),
                bs_btn_step2 = ByteUtil.stringToByte(txt_step2_order.Text),
                bs_start = ByteUtil.stringToByte(txt_step3_order.Text)
            };
            collectionPip.statusEventHandler += collectionStatusChange;

            while (!isDisposed)
            {

                if (collectionPip.status==0 || collectionPip.status==-1)
                {
                    try
                    {
                        collectionPip.connect();
                    }
                    catch (Exception ex)
                    {
                        String msg = ex.Message;
                        if(ex is SocketException)
                        {
                            SocketException ex1 = (SocketException)ex;
                            if (ex1.ErrorCode == 10061)
                            {
                                msg = "没有找到下位机";
                            }

                        }

                        DG dg = delegate ()
                        {
                            label_status.Text = "出错了:"+msg;
                        };
                        Invoke(dg);
                        addMsg("连接上位机失败:" + ex.Message);
                    }
                }
                autoRest.WaitOne(5000);
            }
         
        }

        /// <summary>
        /// 管道连接状态更改事件处理
        /// </summary>
        /// <param name="status"></param>
        private void collectionStatusChange(int status)
        {
            DG dg = delegate ()
            {
                switch (status)
                {
                    case 0:
                        pb_status.Value = 0;
                        label_status.Text = "未初始化";
                        break;
                    case 1:
                        pb_status.Value = 5;
                        label_status.Text = "找到服务器";
                        break;
                    case 2:
                        pb_status.Value = 10;
                        label_status.Text = "连接确认";
                        break;
                    case 3:
                        pb_status.Value = 15;
                        label_status.Text = "有ip连接";
                        break;
                    case 4:
                        pb_status.Value = 20;
                        label_status.Text = "下位机连接确认";
                        btn_user.Enabled = true;
                        break;
                    case 6:
                        pb_status.Value = 25;
                        label_status.Text = "初始化完成";
                        btn_step1.Enabled = true;
                        break;
                    case 8:
                        pb_status.Value = 30;
                        label_status.Text = "第一步完成";
                        btn_step2.Enabled = true;
                        break;
                    case 10:
                        pb_status.Value = 35;
                        label_status.Text = "基本采集条件完成";
                        btn_chart.Enabled = true;
                        skinTabControl1.SelectedIndex = 1;
                        break;
                    case 12:
                        btn_save.Enabled = true;
                        pb_status.Value = 80;
                        label_status.Text = "采集中";
                        new Thread(delegate ()
                        {
                            while (collectionPip.status == 12 || collectionPip.status == 13)
                            {
                                dealData();
                                Thread.Sleep(1);
                            }
                        }).Start();

                        break;
                    case 14:
                        save();
                        pb_status.Value = 100;
                        label_status.Text = "保存成功";
                        reset();

                        break;
                }
            };
            Invoke(dg);

        }


        private void MainFrame_Load(object sender, EventArgs e)
        {
            loadConfig();
            btn_user.Enabled = false;
            btn_step2.Enabled = false;
            btn_chart.Enabled = false;
            skinTabControl1.SelectedIndex = 0;
            new Thread(new ThreadStart(keepConn)).Start();
            reset();
        }


        //private void step(String name)
        //{
        //   // btn_user.Enabled = false;
        //    btn_step1.Enabled = false;
        //    btn_step2.Enabled = false;
        //    btn_chart.Enabled = false;
        //   // btn_system.Enabled = false;
        //    for (int ii = 0; ii < skinTabControl1.TabPages.Count; ii++)
        //    {
        //        //   SkinTabPage skp = (SkinTabPage)skinTabControl1.TabPages[ii];
        //        // skp.IsSelectTab = ii == i - 1;
        //    }
        //    switch (name)
        //    {
        //        case "chart":
        //            btn_chart.Enabled = true;
        //            skinTabControl1.SelectedIndex = 1;
        //            break;
        //        case "user":
        //            btn_user.Enabled = true;
        //            btn_step1.Enabled = true;
        //            skinTabControl1.SelectedIndex = 0;
        //            break;
        //        case "cmd1":
        //            btn_step1.Enabled = true;
        //            skinTabControl1.SelectedIndex = 0;
        //            break;
        //        case "cmd2":
        //            btn_step2.Enabled = true;
        //            break;
        //    }
         

        //}

       private void btn_step2_Click(object sender, EventArgs e)
        {
            btn_step2.Enabled = false;
            collectionPip.sendData_btnStep2();
        }

        //开始采集
        private void btn_chart_Click(object sender, EventArgs e)
        {
            //            collectionPip.sendData(ByteUtil.stringToByte(txt_step3_order.Text));//开始采集命令

            btn_chart.Enabled = false;
            collectionPip.sendData_btnStart();

        }
        private void btn_user_Click(object sender, EventArgs e)
        {
            String user_name = txt_user_name.Text;
            String user_age = txt_user_age.Text;
            String user_sex = radio_user_men.Checked ? "男" : radio_user_women.Checked ? "女" : "";
            String user_comment = txt_user_comment.Text;

            if (String.IsNullOrEmpty(user_name))
            {
                skinTabControl1.SelectedIndex = 0;
                MessageBox.Show("请输入用户姓名");
                return;
            }

            btn_user.Enabled = false;
       
            userModel = new UserModel()
            {
                name = user_name,
                age = user_age,
                sex = user_sex,
                comment = user_comment,
            };

            skinTabControl1.SelectedIndex = 1;
            collectionPip.sendData_userSave();
        }

        private void btn_step1_Click(object sender, EventArgs e)
        {
            btn_step1.Enabled = false;
            try
            {
                //TODO发送数据应该异步处理
                collectionPip.sendData_btnStep1();

            }
            catch (Exception ex)
            {
                MessageBox.Show("出错了:" + ex.Message);
            }

        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        private void loadConfig()
        {
            String user_order = ConfigUtil.readSetting("user_order");
            String step1_order = ConfigUtil.readSetting("step1_order");
            String step2_order = ConfigUtil.readSetting("step2_order");
            String step3_order = ConfigUtil.readSetting("step3_order");
            String collection_speed = ConfigUtil.readSetting("collection_speed");
            String swj_host = ConfigUtil.readSetting("swj_host");
            String swj_port = ConfigUtil.readSetting("swj_port");
            String swj_port2 = ConfigUtil.readSetting("swj_port2");

            int color_line1 = int.Parse(ConfigUtil.readSetting("color_line1"));
            int color_line2 = int.Parse(ConfigUtil.readSetting("color_line2"));
            int color_line3 = int.Parse(ConfigUtil.readSetting("color_line3"));
            int color_line4 = int.Parse(ConfigUtil.readSetting("color_line4"));
            int color_line5 = int.Parse(ConfigUtil.readSetting("color_line5"));
            int color_line6 = int.Parse(ConfigUtil.readSetting("color_line6"));
            int color_line7 = int.Parse(ConfigUtil.readSetting("color_line7"));
            int color_line8 = int.Parse(ConfigUtil.readSetting("color_line8"));

            txt_step1_order.Text = step1_order;
            txt_step2_order.Text = step2_order;
            txt_step3_order.Text = step3_order;
            txt_user_order.Text = user_order;
            txt_collection_speed.Text = collection_speed;
            txt_swj_host.Text = swj_host;
            txt_swj_port.Text = swj_port;
            txt_swj_port2.Text = swj_port2;
            line1.LineColor = Color.FromArgb(color_line1);
            line2.LineColor = Color.FromArgb(color_line2);
            line3.LineColor = Color.FromArgb(color_line3);
            line4.LineColor = Color.FromArgb(color_line4);
            line5.LineColor = Color.FromArgb(color_line5);
            line6.LineColor = Color.FromArgb(color_line6);
            line7.LineColor = Color.FromArgb(color_line7);
            line8.LineColor = Color.FromArgb(color_line8);

            lineControl1.setColor(new int[] {
                color_line1,color_line2,color_line3,color_line4,color_line5,color_line6,color_line7,color_line8
            });

        }

        /// <summary>
        /// 保存配置文件
        /// </summary>
        private void saveConfig()
        {

            String step1_order = txt_step1_order.Text;
            String step2_order = txt_step2_order.Text;
            String step3_order = txt_step3_order.Text;
            String swj_host = txt_swj_host.Text;
            String swj_port = txt_swj_port.Text;
            String swj_port2 = txt_swj_port2.Text;

            int color_line1 = line1.LineColor.ToArgb();
            int color_line2 = line2.LineColor.ToArgb();
            int color_line3 = line3.LineColor.ToArgb();
            int color_line4 = line4.LineColor.ToArgb();
            int color_line5 = line5.LineColor.ToArgb();
            int color_line6 = line6.LineColor.ToArgb();
            int color_line7 = line7.LineColor.ToArgb();
            int color_line8 = line8.LineColor.ToArgb();



            if (!new Regex("^[0-9]+$").IsMatch(swj_port))
            {
                throw new MsgException("上位机连接端口错误(必须为数字)");
            }

            String collection_speed = txt_collection_speed.Text;
            ConfigUtil.changeSetting("step1_order", step1_order);
            ConfigUtil.changeSetting("step2_order", step2_order);
            ConfigUtil.changeSetting("step3_order", step3_order);
            ConfigUtil.changeSetting("collection_speed", collection_speed);
            ConfigUtil.changeSetting("swj_host", swj_host);
            ConfigUtil.changeSetting("swj_port", swj_port);
            ConfigUtil.changeSetting("swj_port2", swj_port2);
            ConfigUtil.changeSetting("color_line1", color_line1+"");
            ConfigUtil.changeSetting("color_line2", color_line2 + "");
            ConfigUtil.changeSetting("color_line3", color_line3 + "");
            ConfigUtil.changeSetting("color_line4", color_line4 + "");
            ConfigUtil.changeSetting("color_line5", color_line5 + "");
            ConfigUtil.changeSetting("color_line6", color_line6 + "");
            ConfigUtil.changeSetting("color_line7", color_line7 + "");
            ConfigUtil.changeSetting("color_line8", color_line8 + "");

        }
      
        private void MainFrame_FormClosing(object sender, FormClosingEventArgs e)
        {
            isDisposed = true;
            collectionPip.Dispose();
            autoRest.Set();
            Application.Exit();
        }

        private void skinLabel3_Click(object sender, EventArgs e)
        {

        }

        private void btn_system_Click(object sender, EventArgs e)
        {
            skinTabControl1.SelectedIndex = 2;
        }


        private List<DataItem> dataItems = new List<DataItem>();
        private void dealData()
        {
            PointData[] pointDatas = collectionPip.readDataItems();
            if (pointDatas.Length == 0)
            {
                return;
            }
            for(var i = 0; i < pointDatas.Length; i++)
            {
                var pointData = pointDatas[i];
                var dataItem = new DataItem()
                {
                    time = pointData.dt.Ticks / 10000,
                    value = pointData.val,
                    type = pointData.type
                };
                lineControl1.pushData(dataItem);//将数据加入到图中
                dataItems.Add(dataItem);
            }
            Thread.Sleep(20);
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton2_Click(object sender, EventArgs e)
        {
            try
            {
                saveConfig();
                MessageBox.Show("保存设置成功,重启软件后生效");
            }
            catch(MsgException e1)
            {
                MessageBox.Show("保存设置失败:" + e1.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存设置失败");
            }
        }

        /// <summary>
        /// 停止且保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_save_Click(object sender, EventArgs e)
        {
            btn_save.Enabled = false;
            collectionPip.sendData_stopAndSave();
        }

        private UserModel userModel;
        private void save()
        {
            var now = DateTime.Now;
            userModel.createTime = now;

            ScanDataModel scanDataModel = new ScanDataModel()
            {
                createTime = now,
                data = bate()
            };

            userDao.addRec(userModel, scanDataModel);
        }

        private void reset()
        {
            dataItems.Clear();
            txt_user_name.ResetText();
            txt_user_age.ResetText();
            txt_user_comment.ResetText();
            radio_user_men.Checked = false;
            radio_user_women.Checked = false;
            lineControl1.reset();
            skinTabControl1.SelectedIndex = 0;
            userModel = null;
        }

        /// <summary>
        /// 将当前图表数据转换为byte数组
        /// </summary>
        /// <returns></returns>
        private byte[] bate()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, dataItems); return ms.GetBuffer();
            }
        }

        private void zDataGridView1_Load(object sender, EventArgs e)
        {
            zDataGridView1.QueryMethod = queryMethod;
        }
        private List<Object> queryMethod(int page, int pageSize, out int total)
        {
            List<UserModel> list =  userDao.queryByPage(page, pageSize, out total);
            List<Object> result = new List<object>();
            list.ForEach(user =>
            {
                result.Add(new
                {
                    id = user.id,
                    姓名 = user.name,
                    性别 = user.sex,
                    年龄 = user.age,
                    备注 = user.comment,
                    创建时间 = user.createTime
                });
            });
            return result;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<dynamic> list = zDataGridView1.getSelections();
            if (list.Count == 0)
            {
                MessageBox.Show("请选择你需要查看的数据");
                return;
            }
            if (list.Count == 0)
            {
                MessageBox.Show("每次只能查看一条数据");
                return;
            }

            int id = list[0].id;
            LookDetailFrame.showDialog(id);
        }
        //历史记录删除
        private void button2_Click(object sender, EventArgs e)
        {
            List<dynamic> list = zDataGridView1.getSelections();
            if (list.Count == 0)
            {
                MessageBox.Show("请选择你需要删除的数据");
                return;
            }
            if (MessageBox.Show("您真的要删除吗？", "确认要删除吗", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                String ids = "";
                list.ForEach(user =>
                {
                    if (ids != "")
                    {
                        ids += ",";
                    };

                    ids += user.id;
                });
                try
                {
                    userDao.delByIds(ids);
                    MessageBox.Show("删除成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除出错:" + ex.Message);
                }
                finally
                {
                    zDataGridView1.reload();
                }
            }

        }

        private void skinTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (skinTabControl1.SelectedIndex == 3)
            {
                zDataGridView1.reload();
            }
        }

        private void skinLine1_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if(dr == DialogResult.OK)
            {
                line1.LineColor = colorDialog1.Color;
            }
        }

        private void line2_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line2.LineColor = colorDialog1.Color;
            }
        }

        private void line3_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line3.LineColor = colorDialog1.Color;
            }
        }

        private void line4_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line4.LineColor = colorDialog1.Color;
            }
        }

        private void line5_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line5.LineColor = colorDialog1.Color;
            }
        }

        private void line6_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line6.LineColor = colorDialog1.Color;
            }
        }

        private void line7_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line7.LineColor = colorDialog1.Color;
            }
        }

        private void line8_Click(object sender, EventArgs e)
        {
            var dr = colorDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                line8.LineColor = colorDialog1.Color;
            }
        }

        private void label_status_Click(object sender, EventArgs e)
        {

        }
    }
}
